<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>发布订阅模式</title>
</head>
<body>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    // 事件触发器
    class EventEmitter {
      constructor() {
        // 存储事件名跟事件处理函数 { 'click': [fn1, fn2] }
        this.subs = Object.create(null)
      }
      // 注册事件
      // vm.$on('data', () => {})
      $on(eventType, handler) {
          // 判断 eventType 是否在 this.subs 里，赋值为空数组，确保是数组对象，然后把事件处理函数放到数组里
          this.subs[eventType] = this.subs[eventType] || []
          this.subs[eventType].push(handler)
      }
      // 触发事件
      $emit(eventType) {
        // 判断 this.subs 是否有 eventType 属性
        if (this.subs[eventType]) {
          this.subs[eventType].forEach(handler => {
            handler()
          })
        }
      }
    }
    // 测试
    let em = new EventEmitter()
    em.$on('click', () => {
      console.log('click1')
    })
    em.$on('click', () => {
      console.log('click2')
    })
    em.$emit('click')
  </script>
</body>
</html>